/*
 * Copyright (c) 2015. For Intelligent Group.
 */

package com.intelligent.ispc.web.controller;

import com.intelligent.ispc.common.dto.JsonResponseDto;
import com.intelligent.ispc.common.mapper.JsonMapper;
import com.intelligent.ispc.common.utils.ApplicationException;
import com.intelligent.ispc.common.utils.ExceptionMessages;
import com.intelligent.ispc.common.utils.StringUtils;
import com.intelligent.ispc.common.web.Servlets;
import com.intelligent.ispc.core.dto.BaseDto;
import com.intelligent.ispc.core.dto.StationDto;
import com.intelligent.ispc.core.dto.TestItemDto;
import com.intelligent.ispc.core.service.SpcAnalysisService;
import com.intelligent.ispc.core.service.SpcExportService;
import com.intelligent.ispc.external.rcall.dto.ControlDataDto;
import com.intelligent.ispc.external.rcall.dto.NormalDistributionDto;
import com.intelligent.ispc.utils.Constant;
import com.intelligent.ispc.utils.SystemConfig;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Peter.Li on 2015/10/21.
 */
@Controller
@RequestMapping(value = "/export")
public class SpcExportController {

    @Autowired
    private SpcAnalysisService spcAnalysisService;

    @Autowired
    private SpcExportService spcExportService;

    @Autowired
    private SystemConfig systemConfig;

    protected JsonMapper mapper = JsonMapper.nonDefaultMapper();

    @ResponseBody
    @RequestMapping(value = "multiple/ndc")
    public JsonResponseDto exportSpecificND(ServletRequest request, Model model) {
        Subject subject = SecurityUtils.getSubject();
        if (!subject.isPermitted("analysis:spc:export")) {
            return JsonResponseDto.FAILURE().setMessage(ExceptionMessages.EXCEPTION_NO_PERMISSION);
        }

        try {
            Map<String, Object> searchParam = Servlets.getParametersStartingWith(request, "search_");
            setParameters(searchParam);

            searchParam.put("fileType", "xls");
            spcExportService.exportMultiItemsChartsToExcel(searchParam);
        } catch (ApplicationException e) {
            return JsonResponseDto.FAILURE().setMessage(e.getMessage());
        }

        return JsonResponseDto.SUCCESS();
    }

    @ResponseBody
    @RequestMapping(value = "single/all")
    public JsonResponseDto exportSingleND(ServletRequest request, Model model) {
        Subject subject = SecurityUtils.getSubject();
        if (!subject.isPermitted("analysis:spc:export")) {
            return JsonResponseDto.FAILURE().setMessage(ExceptionMessages.EXCEPTION_NO_PERMISSION);
        }

        try {
            Map<String, Object> searchParam = Servlets.getParametersStartingWith(request, "search_");

            setParameters(searchParam);
            spcExportService.exportSingleItemChartsToExcel(searchParam);
        } catch (ApplicationException e) {
            return JsonResponseDto.FAILURE().setMessage(e.getMessage());
        }

        return JsonResponseDto.SUCCESS();
    }

    private Map<String, Object> setParameters(Map<String, Object> searchParam) {
        StringBuilder stationId = new StringBuilder();
        StringBuilder slotNo = new StringBuilder();

        if (searchParam.containsKey("stationIdOrSlotNo")) {
            List<StationDto> stationDtoList = mapper.fromJson((String) searchParam.get("stationIdOrSlotNo"), mapper.contructCollectionType(List.class, StationDto.class));
            if (stationDtoList != null && !stationDtoList.isEmpty()) {
                for (int i = 0; i < stationDtoList.size(); i++) {
                    if (StringUtils.isNotBlank(stationDtoList.get(i).getStationId())) {
                        stationId.append(stationDtoList.get(i).getStationId()).append(", ");
                    }
                    if (stationDtoList.get(i).getSlotNos() != null && !stationDtoList.get(i).getSlotNos().isEmpty()) {
                        for (String slot : stationDtoList.get(i).getSlotNos()) {
                            slotNo.append(stationDtoList.get(i).getStationId()).append("-").append(slot).append(", ");
                        }
                    }
                }
            }
        }

        if (StringUtils.isNotBlank(stationId)) {
            searchParam.put("stationId", stationId.substring(0, stationId.length()-2));
        }

        if (StringUtils.isNotBlank(slotNo)) {
            searchParam.put("slotNo", slotNo.substring(0, slotNo.length()-2));
        }
        return searchParam;
    }

}
